package com.wg.springboothandler.Interceptor;

import com.wg.springboothandler.model.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Author WuGang
 * @Date 2021/10/20 18:58
 * @Version 1.0
 */
public class UserInterceptor implements HandlerInterceptor {
//    此方法编写拦截规则
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器--------------------------------");
//        从session中取用户信息
        User  user= (User) request.getSession().getAttribute("user");
        if (user==null){
//            未登录 返回一个到另一个页面  下面是页面地址
            response.sendRedirect(request.getContextPath()+"/user/error");
//            false表示拦截
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
